#pragma once
#include <iostream>
#include <pthread.h>


namespace MutexModule
{
    class mutex
    {
    public:
        // 锁资源不可以被拷贝和赋值 所以要把这些构造全部删除
        mutex(const mutex& mtx) = delete;
        const mutex& operator=(const mutex& mtx) = delete;
        
        mutex()
        {
            // 对锁局部锁进行初始化
            int n = pthread_mutex_init(&_mtx, nullptr);
            if(n != 0)
            {
                std::cout << "creat mutex fail! " << std::endl;
                exit(n);
            }
        }   

        void lock()
        {
            int n = pthread_mutex_lock(&_mtx);
            if(n != 0)
            {
                std::cout << "use mutex fail!" << std::endl;
                exit(n);
            }
        }

        void unlock()
        {
            int n = pthread_mutex_unlock(&_mtx);
            if(n != 0)
            {
                std::cout << "unlock mutex fail!" << std::endl;
                exit(n);
            }
        }

        pthread_mutex_t* getlock()
        {
            return &_mtx;
        }

        ~mutex()
        {
            int n = pthread_mutex_destroy(&_mtx);
            if(n != 0)
            {
                std::cout << "destroy mutex fail!" << std::endl;
                exit(n);
            }
        }
    private:
        pthread_mutex_t _mtx;
    };

    class Lockguard
    {
    public:
        Lockguard(mutex& mtx)
        :_lockguard(mtx)
        {
            _lockguard.lock();
        }
        ~Lockguard()
        {
            _lockguard.unlock();
        }
    private:
        mutex& _lockguard;
    };
}